//
//  JKCreateQRCodeViewController.swift
//  JKWeibo
//
//  Created by albert on 16/5/13.
//  Copyright © 2016年 albert. All rights reserved.
//  个人名片 展示个人的二维码

import UIKit

class JKCreateQRCodeViewController: UIViewController {

    /** 我的二维码 */
    @IBOutlet weak var myQRCodeImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 1.创建过滤器
        let filter = CIFilter(name: "CIQRCodeGenerator")
        
        // 2.恢复默认
        filter?.setDefaults()
        
        // 3.给过滤器添加数据（正则表达式/帐号和密码）
        let dataStr = "hhaha  http://www.baidu.com"
        let data = dataStr.dataUsingEncoding(NSUTF8StringEncoding)
        filter?.setValue(data, forKey: "inputMessage")
        
        // 4.获取输出的二维码
        guard let ouputImage = filter?.outputImage else {
            return
        }
        
        // 5.显示二维码
        //myQRCodeImageView.image = UIImage(CIImage: ouputImage)
        myQRCodeImageView.image = createNonInterpolatedUIImageFormCIImage(ouputImage, size: 200)
    }
    
    /**
     生成高清二维码
     
     - parameter image: 需要生成原始图片
     - parameter size:  生成的二维码的宽高
     */
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
        let extent: CGRect = CGRectIntegral(image.extent)
        let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
        
        // 1.创建bitmap;
        let width = CGRectGetWidth(extent) * scale
        let height = CGRectGetHeight(extent) * scale
        let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
        let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)
        
        CGContextSetInterpolationQuality(bitmapRef,  CGInterpolationQuality.None)
        CGContextScaleCTM(bitmapRef, scale, scale);
        CGContextDrawImage(bitmapRef, extent, bitmapImage);
        
        // 2.保存bitmap到图片
        let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
        
        return UIImage(CGImage: scaledImage)
    }
}
